from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from auth_two import models
import uuid


class RegisterView(APIView):
	def post(self, request):
		user = request.data.get('user')
		pwd = request.data.get('pwd', '')
		re_pwd = request.data.get('re_pwd')
		if user and pwd:
			if pwd != re_pwd:
				return Response({"error": '两次密码不一致', 'error_no': 2})
			# 校验通过 插入数据库
			user = models.UserInfo.objects.create(name=user, pwd=pwd)
			return Response({"msg": '注册成功', 'error_no': 0})
		else:
			return Response({"error": '无效的参数', 'error_no': 1})


class LoginView(APIView):
	def post(self, request):
		user = request.data.get('user')
		pwd = request.data.get('pwd', '')
		if user and pwd:
			user_obj = models.UserInfo.objects.filter(name=user, pwd=pwd).first()
			if not user_obj:
				return Response({"error": '用户名或密码错误', 'error_no': 2})
			# 认证成功
			# 生成token字符串  返回token
			token = uuid.uuid1().hex
			user_obj.token = token
			user_obj.save()  # 将token 保存到用户表
			return Response({"token": token, 'error_no': 0})

		else:
			return Response({"error": '无效的参数', 'error_no': 1})


from auth_two.auth import MyAuth
from auth_two.permission import VipPermission

class TestView(APIView):
	authentication_classes = [MyAuth]
	permission_classes = [VipPermission]

	def get(self, request):


		return Response({'msg': "认证后才能看到此内容"})

# {
# "user":"alex",
# "pwd":"dsb"
# }
